package cn.com.nes.site.service.crm.customer.impl;

import cn.com.nes.common.exception.IllegalBusinessException;
import cn.com.nes.common.exception.MissBusinessParameterException;
import cn.com.nes.common.util.CopyUtils;
import cn.com.nes.common.util.OssUtil;
import cn.com.nes.mybatis.agent.crm.entity.CustomerFile;
import cn.com.nes.mybatis.agent.crm.mapper.CustomerFileMapper;
import cn.com.nes.mybatis.agent.system.entity.TUser;
import cn.com.nes.site.entity.em.crm.customer.CustomerFileTypeEnum;
import cn.com.nes.site.service.crm.customer.CrmCustomerService;
import cn.com.nes.site.service.crm.customer.CustomerFileService;
import cn.com.nes.site.service.crm.customer.bo.CustomerFileBO;
import cn.com.nes.site.service.crm.customer.dto.CustomerDTO;
import cn.com.nes.site.service.crm.customer.dto.CustomerFileDTO;
import cn.com.nes.site.service.system.user.SystemUserService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
public class CustomerFileServiceImpl extends ServiceImpl<CustomerFileMapper, CustomerFile> implements CustomerFileService {

    @Resource
    private CrmCustomerService crmCustomerService;

    @Resource
    private SystemUserService systemUserService;

    @Override
    public List<CustomerFileDTO> getCustomerFileList(CustomerFileBO customerFileBo) {
        if (StrUtil.isBlank(customerFileBo.getCustomerUuid())) {
            throw new MissBusinessParameterException("customerUuid must not blank");
        }
        return this.baseMapper.getCustomerFileList(customerFileBo.getCustomerUuid());
    }

    /**
     * 客户文件分页
     * @param customerFileBo
     * @return
     * @throws Exception
     */
    @Override
    public Page<CustomerFileDTO> getCustomerFilePage(CustomerFileBO customerFileBo) throws Exception {
        QueryWrapper<CustomerFile> wrapper = new QueryWrapper<>();
        wrapper.eq("deleted", false);
        if (StrUtil.isNotEmpty(customerFileBo.getCustomerUuid())) {
            wrapper.eq("customer_uuid", customerFileBo.getCustomerUuid());
        }
        if (ObjectUtil.isNotNull(customerFileBo.getCustomerFileType())) {
            wrapper.eq("file_type", customerFileBo.getCustomerFileType().getKey());
        }
        wrapper.orderByDesc("gmt_modified");
        // 分页查询数据 - 在使用时才创建分页page
        Page<CustomerFile> page = new Page<>(customerFileBo.getPageid(), customerFileBo.getPagesize());
        Page<CustomerFile> customerFilePage = (Page<CustomerFile>) this.page(page, wrapper);
        // 转换返回值类型
        Page<CustomerFileDTO> customerFileDTOPage = CopyUtils.copyPage(customerFilePage, CustomerFileDTO.class);

        // 准备容器
        Map<String, String> customerNameMap = new HashMap<>();
        // 遍历处理相关字段
        for (CustomerFileDTO customerFile : customerFileDTOPage.getRecords()) {
            // 处理客户姓名
            if (ObjectUtil.isNull(customerNameMap.get(customerFile.getCustomerUuid()))) {
                CustomerDTO customerInfo = crmCustomerService.getCustomerById(customerFile.getCustomerUuid());
                customerNameMap.put(customerFile.getCustomerUuid(), customerInfo.getCustomerName());
            }
            customerFile.setCustomerName(customerNameMap.get(customerFile.getCustomerUuid()));

            // 处理文件类型名称
            customerFile.setFileTypeName(CustomerFileTypeEnum.getVal(customerFile.getFileType()));

            // 处理文件路径
            if (StrUtil.isNotBlank(customerFile.getFilePath())) {
                String imgSignURL = OssUtil.getFileSignURL(customerFile.getFilePath(), 0);
                customerFile.setRealFilePath(imgSignURL);
            }

            // 处理上传人信息
            TUser userInfo = systemUserService.getUserInfoByUserId(customerFile.getGmtCreateId());
            customerFile.setCreateUserNickName(userInfo.getNickName());
        }
        return customerFileDTOPage;
    }

    /**
     * 客户文件
     * @param customerFileBo
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CustomerFile saveCustomerFile(CustomerFileBO customerFileBo) throws Exception {
        CustomerFile customerFile = new CustomerFile();
        BeanUtils.copyProperties(customerFileBo, customerFile);
        if (customerFileBo.isAdd()) {
            customerFile.setGmtCreate(customerFileBo.getOperateDate());
            customerFile.setGmtCreateId(customerFileBo.getOperateUserId());
            customerFile.setDeleted(false);
        }
        customerFile.setFileType(customerFileBo.getCustomerFileType().getKey());
        customerFile.setGmtModified(customerFileBo.getOperateDate());
        customerFile.setGmtModifiedId(customerFileBo.getOperateUserId());
        this.saveOrUpdate(customerFile);
        return customerFile;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delCustomerFile(CustomerFileBO customerFileBO) {
        if (ObjectUtil.isNull(customerFileBO.getId())) {
            throw new MissBusinessParameterException("id must not null");
        }

        CustomerFile customerFile = new CustomerFile();
        customerFile.setId(customerFileBO.getId());
        customerFile.setDeleted(true);
        customerFile.setGmtModifiedId(customerFileBO.getOperateUserId());
        customerFile.setGmtModified(customerFileBO.getOperateDate());

        boolean success = this.updateById(customerFile);
        if (!success) {
            throw new IllegalBusinessException("删除客户文件失败!");
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delCustomerFile(String customerUUid){
        if(StrUtil.isEmpty(customerUUid)){
            throw new MissBusinessParameterException("id must not null");
        }
        this.baseMapper.delCustomerFile(customerUUid);
    }
    @Override
    public List<CustomerFile> saveCustomerFiles(List<CustomerFileBO> customerFileBOList) throws Exception {
        if (CollUtil.isEmpty(customerFileBOList)) {
            return Collections.emptyList();
        }
        List<CustomerFile> customerFileList = new ArrayList<>();
        for (CustomerFileBO customerFileBO : customerFileBOList) {
            customerFileList.add(saveCustomerFile(customerFileBO));
        }
        return customerFileList;
    }


}
